'''
Created on Oct 26, 2009

@author: ca3jmaupas
'''

from django.utils import simplejson as json
from server.RequestHandler import SessionHandler
from model.Revision import Revision
from server.Utils import SID_ID, HTTP_UNAUTHORIZED
import urllib
import logging

WS_ID="ws"
FUNCTION_LIST=["listServers","add","getTime","start"] # could dir(RPCMethods: authoirized

# send by client
class ClientQuery:
    jsonrpc = "2.0"
    method = ""
    params = {}
    id = ""
         
# server response
class ServerResult:
    jsonrpc = "2.0"
    result = {} 
    id = ""

class ServerError:
    jsonrpc = "2.0"
    class error:
        code=0
        message=""
        data=""
    id = ""

## Main calss to handel webservices
#
# 
class WebService(SessionHandler): 

    def _checkPath(self):
        logging.info("Body: ["+self.request.body+"] "+
                     "Query: ["+self.request.query_string+"] "+
                     "Path: ["+str(self.request.path)+"] ") 
        if self.path_list[0] != WS_ID: self.abort("Invalid ws path")
        elif len(self.path_list) <2: self.abort("Invalid ws function")
        else:
            self.action = urllib.unquote(self.path_list[1])
            if not self.action in FUNCTION_LIST: self.abort("Invalid function")
            else:
                if not self.action or self.action[0] == '_': self.abort("Access Denied")
                else: return True
#          if (users.IsCurrentUserAdmin() or user.email() == email):
#            self.args=path_list[1:]
#            return path_list
#          else:
        return False

    def get_args(self):
        '''
        a0=2&a1=3
        '''
        args = ()
        while True:
            key = 'a%d' % len(args)
            val = self.request.get(key)
            if val:
                args += (json.loads(val),)
            else:
                break
        return args

    def getArgs(self):
        '''
        n=2&m=3
        '''
        #return [json.loads(self.request.get(a)) for a in self.request.arguments() if not a in (SID_ID)]
        args = ()
        for a in self.request.arguments():
            if not a in (SID_ID):
                val = self.request.get(a)
                if val:
                    args += (json.loads(val),)
        return args

    def abort(self,s,http=HTTP_UNAUTHORIZED):
        response = {}
        response['version'] = Revision.revisionNumber
        if self.senderID: response['ID'] = self.senderID
        #response['sidCode'] = SID_ID
        #response['sidValue'] = self.sid # self.session.nextID
        response['error'] = s
        result=json.dumps(response)
#        self.headers(len(result))
        logging.error("Internal error: "+str(s))
        self.error(http)
        self.response.out.write(result)

    def ok (self,s=""):
        response = {}
        response['version'] = Revision.revisionNumber
        if self.senderID: response['ID'] = self.senderID
        if self.session.nextID:
            response['sidCode'] = SID_ID
            response['sidValue'] = self.session.nextID
        response['result'] = s
        result=json.dumps(response)
        self.headers(len(result))
        logging.info('result :'+str(result))
        return (result)
